/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.constant.CommonConstant;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.domain.IsfdModelManagementCalculateRefLoad;
import com.comac.ins.isfd.domain.IsfdModelManagementLoad;
import com.comac.ins.isfd.domain.bo.IsfdModelManagementLoadBo;
import com.comac.ins.isfd.domain.vo.IsfdModelManagementCalculateFileVo;
import com.comac.ins.isfd.domain.vo.IsfdModelManagementLoadVo;
import com.comac.ins.isfd.domain.vo.IsfdModelManagementTaskVo;
import com.comac.ins.isfd.mapper.IsfdModelManagementCalculateFileMapper;
import com.comac.ins.isfd.mapper.IsfdModelManagementCalculateRefLoadMapper;
import com.comac.ins.isfd.mapper.IsfdModelManagementLoadMapper;
import com.comac.ins.isfd.mapper.IsfdModelManagementTaskMapper;
import com.comac.ins.isfd.service.IIsfdModelManagementLoadService;
import com.comac.ins.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.comac.ins.common.mybatis.core.mapper.BaseMapperPlus.log;

/**
 * 模型管理载荷Service业务层处理
 *
 * @author Lion Li
 * @date 2024-08-19
 */
@RequiredArgsConstructor
@Service
public class IsfdModelManagementLoadServiceImpl implements IIsfdModelManagementLoadService {

    private final IsfdModelManagementLoadMapper baseMapper;

    private final ISysDictDataService iSysDictDataService;
    @Autowired
    private IsfdModelManagementCalculateRefLoadMapper isfdModelManagementCalculateRefLoadMapper;
    @Autowired
    private IsfdModelManagementCalculateFileMapper isfdModelManagementCalculateFileMapper;
    @Autowired
    private IsfdModelManagementTaskMapper isfdModelManagementTaskMapper;


    /**
     * 查询模型管理载荷
     *
     * @param id 主键
     * @return 模型管理载荷
     */
    @Override
    public IsfdModelManagementLoadVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询模型管理载荷列表
     *
     * @param bo 查询条件
     * @return 模型管理载荷分页列表
     */
    @Override
    public TableDataInfo<IsfdModelManagementLoadVo> queryPageList(IsfdModelManagementLoadBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        LambdaQueryWrapper<IsfdModelManagementLoad> lqw = buildQueryWrapper(bo);
        Page<IsfdModelManagementLoadVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的模型管理载荷列表
     *
     * @param bo 查询条件
     * @return 模型管理载荷列表
     */
    @Override
    public List<IsfdModelManagementLoadVo> queryList(IsfdModelManagementLoadBo bo) {
        LambdaQueryWrapper<IsfdModelManagementLoad> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<IsfdModelManagementLoadVo> queryListByCalculateId(Long calculateId) {
        List<IsfdModelManagementCalculateRefLoad> isfdModelManagementCalculateRefLoads = isfdModelManagementCalculateRefLoadMapper
            .selectList(new LambdaQueryWrapper<IsfdModelManagementCalculateRefLoad>()
                .eq(IsfdModelManagementCalculateRefLoad::getCalculateId, calculateId));
        if (CollectionUtils.isEmpty(isfdModelManagementCalculateRefLoads)) {
            return new ArrayList<>();
        }
        List<Long> loadIds = isfdModelManagementCalculateRefLoads.stream().map(IsfdModelManagementCalculateRefLoad::getLoadId).toList();
        return baseMapper.selectVoBatchIds(loadIds);
    }

    private LambdaQueryWrapper<IsfdModelManagementLoad> buildQueryWrapper(IsfdModelManagementLoadBo bo) {
        LambdaQueryWrapper<IsfdModelManagementLoad> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getModelNumber()), IsfdModelManagementLoad::getModelNumber, bo.getModelNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), IsfdModelManagementLoad::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增模型管理载荷
     *
     * @param bo 模型管理载荷
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdModelManagementLoadBo bo, MultipartFile file) {
        String prefixPath = iSysDictDataService.selectDictValueByTypeAndLabel(CommonConstant.SYS_COMMON_DICT_TYPE,
            CommonConstant.MODEL_MANAGEMENT_LOAD_DATA_PREFIX);
        if (StringUtils.isBlank(prefixPath)) {
            throw new BaseException("载荷数据存储路径前缀未配置，请到字典管理中配置，并重试.");
        }
        try {
            // 文件操作
            String fileName = file.getOriginalFilename();
            String filePath = prefixPath + System.currentTimeMillis();
            String fileUrl = filePath + "/" + fileName;
            Path targetPath = Paths.get(fileUrl);
            File dir = targetPath.getParent().toFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Files.write(targetPath, file.getBytes());
            IsfdModelManagementLoad add = MapstructUtils.convert(bo, IsfdModelManagementLoad.class);
            if (add != null) {
                add.setFileName(fileName);
                add.setFileUrl(fileUrl);
                // 保留5位小数
                String resultStr = String.format("%.5f", (double) file.getSize() / 1024);
                add.setFileSize(Double.parseDouble(resultStr));
            }
            return baseMapper.insert(add) > 0;
        } catch (Exception e) {
            log.error("上传载荷数据失败", e);
            throw new BaseException("上传载荷数据失败");
        }
    }

    /**
     * 修改模型管理载荷
     *
     * @param bo 模型管理载荷
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdModelManagementLoadBo bo) {
        IsfdModelManagementLoad update = MapstructUtils.convert(bo, IsfdModelManagementLoad.class);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 校验并批量删除模型管理载荷信息
     *
     * @param ids 待删除的主键集合
     * @return 是否删除成功
     */
    @Transactional
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        for (Long id : ids) {
            // 删除主表
            baseMapper.deleteById(id);
            // 删除和计算的关联关系表
            isfdModelManagementCalculateRefLoadMapper.delete(new LambdaQueryWrapper<IsfdModelManagementCalculateRefLoad>()
                .eq(IsfdModelManagementCalculateRefLoad::getLoadId, id));
        }
        return Boolean.TRUE;
    }

    @Override
    public String preDelete(Collection<Long> ids) {
        String result = null;
        for (Long id : ids) {
            // 查主表
            IsfdModelManagementLoad isfdModelManagementLoad = baseMapper.selectById(id);
            // 查询和计算的关联关系表
            List<IsfdModelManagementCalculateRefLoad> isfdModelManagementCalculateRefLoads = isfdModelManagementCalculateRefLoadMapper.selectList(new LambdaQueryWrapper<IsfdModelManagementCalculateRefLoad>()
                .eq(IsfdModelManagementCalculateRefLoad::getLoadId, id));
            if (CollectionUtils.isNotEmpty(isfdModelManagementCalculateRefLoads)) {
                for (IsfdModelManagementCalculateRefLoad isfdModelManagementCalculateRefLoad : isfdModelManagementCalculateRefLoads) {
                    IsfdModelManagementCalculateFileVo isfdModelManagementCalculateFileVo = isfdModelManagementCalculateFileMapper.selectVoById(isfdModelManagementCalculateRefLoad.getCalculateId());
                    if (isfdModelManagementCalculateFileVo == null) {
                        continue;
                    }
                    IsfdModelManagementTaskVo isfdModelManagementTaskVo = isfdModelManagementTaskMapper.selectVoById(isfdModelManagementCalculateFileVo.getTaskId());
                    if (isfdModelManagementTaskVo == null) {
                        continue;
                    }
                    String taskName = isfdModelManagementTaskVo.getTaskName();
                    result = "文件名为：" + isfdModelManagementLoad.getFileName() + "的载荷文件，至少和模型组建任务为:" + taskName + "的计算存在关联关系，确认是否删除？";
                    break;
                }
            }
        }
        return result;
    }

    /**
     * 批量查询载荷数据
     *
     * @param ids
     * @return
     */
    @Override
    public List<IsfdModelManagementLoadVo> queryByBatchIds(List<Long> ids) {
        return baseMapper.selectVoBatchIds(ids);
    }
}
